/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.auth.sys.service.impl;

import com.arisgo.cloud.auth.login.granter.configurer.ManagerConfigurer;
import com.arisgo.cloud.auth.sys.entity.Menu;
import com.arisgo.cloud.auth.sys.mapper.MenuMapper;
import com.arisgo.cloud.auth.sys.service.MenuService;
import com.arisgo.cloud.auth.sys.vo.MenuVo;
import com.arisgo.cloud.core.redis.UserInfo;
import com.arisgo.cloud.web.mybatis.service.CloudServiceImpl;
import com.arisgo.cloud.web.param.Param;
import com.arisgo.cloud.web.param.Search;
import com.arisgo.cloud.web.utils.RequestUtil;
import com.arisgo.cloud.web.utils.TreeUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 菜单
 *
 * @author Arisgo
 * @since 2024-06-14
 */
@Service
@AllArgsConstructor
public class MenuServiceImpl extends CloudServiceImpl<MenuMapper, Menu, MenuVo> implements MenuService {

    private final ManagerConfigurer managerConfigurer;

    @Override
    public Menu getInstanceModel() {
        return new Menu();
    }

    @Override
    public MenuVo getInstanceVo() {
        return new MenuVo();
    }

    @Override
    public List<MenuVo> treePageMenus(Search search) {
        // 超级管理员，菜单管理页面展示所有菜单
        if (managerConfigurer.getUserId().equals(RequestUtil.getUserId())) {
            return TreeUtil.convertTree(this.findByParams(search));
        }
        // 租户所有者，菜单管理页面展示已开通的所有功能点
        // 其他用户，取 功能包+角色 的并集
        return treeLeftMenus(search);
    }

    @Override
    public List<MenuVo> treeLeftMenus(Search search) {
        search.addTenantIdParam(RequestUtil.getTenantId());
        search.addParam(Param.creator(UserInfo.IS_OWNER, RequestUtil.getUser().isOwner()));
        search.addParam(Param.creator(UserInfo.USER_ID, RequestUtil.getUserId()));
        return TreeUtil.convertTree(this.mapper.findMenusByParams(search.convertMap()));
    }

}
